package com.yifeng.dao.impl;

import com.yifeng.common.SqlStatements;
import com.yifeng.dao.ResourceDao;
import com.yifeng.model.Resource;
import com.yifeng.util.JdbcUtil;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


public class ResourceDaoImpl implements ResourceDao {

    /*
    负责人：未知

    功能：查询所有资源，支持资源管理界面的分页展示

    参数：offset - 数据偏移量, pageSize - 每页记录数

    返回值：资源对象列表，按上传时间倒序排列，异常时返回空列表
    */
    @Override
    public List<Resource> findResourceList() {


        String sql = SqlStatements.RESOURCE_FIND_ALL;
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            try (ResultSet rs = ps.executeQuery()) {
                return mapResultSetToList(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }



    /*
    负责人：未知

    功能：按关键词搜索资源，支持资源管理中的搜索功能

    参数：keyword - 搜索关键词, offset - 数据偏移量, pageSize - 每页记录数

    返回值：匹配关键词的资源对象列表，异常时返回空列表
    */
    @Override
    public List<Resource> searchByKeyword(String keyword) {

        String sql = SqlStatements.RESOURCE_SEARCH_PAGINATED;
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, "%" + keyword + "%");
            try (ResultSet rs = ps.executeQuery()) {
                return mapResultSetToList(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }



    /*
    负责人：未知

    功能：插入新资源记录，用于资源上传功能，支持获取自增主键

    参数：resource - 包含资源信息的Resource对象

    返回值：插入成功返回true，失败返回false
    */
    @Override
    public boolean insert(Resource resource) {
        String sql = SqlStatements.RESOURCE_INSERT;


        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            ps.setString(1, resource.getFileName());
            ps.setString(2, resource.getUploader());
            ps.setString(3, resource.getType());
            ps.setString(4, resource.getFilePath());
            ps.setLong(5, resource.getFileSize());
            ps.setInt(6, resource.getDownloadCount() != null ? resource.getDownloadCount() : 0);

            int rows = ps.executeUpdate();
            if (rows > 0) {
                try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        resource.setResourceId(generatedKeys.getInt(1));
                    }
                }
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /*
    负责人：未知

    功能：删除资源记录，实现资源管理中的删除功能

    参数：resourceId - 资源唯一标识ID

    返回值：删除成功返回true，失败返回false
    */
    @Override
    public boolean delete(int resourceId) {
        String sql = SqlStatements.RESOURCE_DELETE;
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, resourceId);
            return ps.executeUpdate() == 1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /*
       负责人：未知

       功能：根据资源ID查询资源记录，实现资源管理中的查询功能

       参数：resourceId - 资源唯一标识ID

       返回值：查询成功返回对应的Resource对象，未找到或发生异常返回null
   */
    @Override
    public Resource findResourceById(Integer resourceId) {
        String sql = SqlStatements.RESOURCE_FIND_BY_ID;
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
              ps.setInt(1, resourceId);
            try (ResultSet rs = ps.executeQuery()) {

                    return mapResultSetToResource(rs);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean incrementDownloadCount(int resourceId) {
        String sql =SqlStatements.RESOURCE_UPDATE_DOWNLOADCOUNT_BYID;
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, resourceId);
            return ps.executeUpdate() == 1;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    /*
        负责人：未知

        功能：将ResultSet结果集转换为单个Resource对象，用于单条记录查询的公共处理逻辑

        参数：rs - 数据库查询结果集（预期只包含一行数据）

        返回值：Resource对象，若结果集为空则返回null
    */
    private Resource mapResultSetToResource(ResultSet rs) throws SQLException {
        if (rs.next()) {
            Resource resource = new Resource();
            resource.setResourceId(rs.getInt("resource_id"));
            resource.setFileName(rs.getString("file_name"));
            resource.setUploader(rs.getString("uploader"));
            resource.setType(rs.getString("type"));
            resource.setFilePath(rs.getString("file_path"));
            resource.setFileSize(rs.getLong("file_size"));
            // MySQL DATETIME -> LocalDateTime
            resource.setUploadTime(rs.getObject("upload_time", LocalDateTime.class));
            resource.setDownloadCount(rs.getInt("downloadCount"));
            return resource;
        }
        return null;
    }
    /*
    负责人：未知

    功能：将ResultSet结果集转换为Resource对象列表，用于多个查询方法的公共处理逻辑

    参数：rs - 数据库查询结果集

    返回值：Resource对象列表
    */
    private List<Resource> mapResultSetToList(ResultSet rs) throws SQLException {
        List<Resource> list = new ArrayList<>();
        while (rs.next()) {
            Resource resource = new Resource();
            resource.setResourceId(rs.getInt("resource_id"));
            resource.setFileName(rs.getString("file_name"));
            resource.setUploader(rs.getString("uploader"));
            resource.setType(rs.getString("type"));
            resource.setFilePath(rs.getString("file_path"));
            resource.setFileSize(rs.getLong("file_size"));
            // MySQL DATETIME -> LocalDateTime
            resource.setUploadTime(rs.getObject("upload_time", LocalDateTime.class));
            resource.setDownloadCount(rs.getInt("downloadCount"));
            list.add(resource);
        }
        return list;
    }
}